package com.zking.filter;

import com.zking.dao.UserDao;
import com.zking.entity.User;
import com.zking.util.RedirectMsg;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import com.zking.config.config;


public class AdminFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {

        if(config.is_debug){
            chain.doFilter(request, response);
            return;
        }

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String uri = httpRequest.getRequestURI();


        HttpSession session = httpRequest.getSession(false);
        boolean loggedIn = session != null && session.getAttribute("user")!=null;

        if (!loggedIn){
            httpRequest.setAttribute("msg", RedirectMsg.notLogin);
            httpRequest.setAttribute("pageName", RedirectMsg.loginPageName);
            httpRequest.setAttribute("url", "../"+RedirectMsg.loginUrl);
            httpRequest.getRequestDispatcher("redirect.jsp").forward(request, response);
            return;
        }

        User user1 = (User) session.getAttribute("user");
        User user2 = UserDao.getUserById(user1.getEu_user_id());

        if(user2!=null && user2.getEu_status()==2){
            chain.doFilter(request, response);
        }else{
            httpRequest.setAttribute("msg", RedirectMsg.adminError);
            httpRequest.setAttribute("pageName", RedirectMsg.indexPageName);
            httpRequest.setAttribute("url", "../"+RedirectMsg.indexUrl);
            httpRequest.getRequestDispatcher("redirect.jsp").forward(request, response);
        }

    }
}
